//
//  BaseController.swift
//  vmes
//
//  Created by user on 2021/10/29.
//

import UIKit
import Alamofire

class BaseController: UIViewController {
    
    
    let appId = "1598701764"
    
    func detectionOfUpdate(){
        //获取当前手机安装使用的版本号
        let localVersion:String = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        print(localVersion)
        //获取App Store上app的最新版本
        let url = "http://itunes.apple.com/cn/lookup?id=\(appId)"
        AF.request(URL(string: url)!, method: .post, parameters: nil)
            .responseJSON { response in
                print(response)
                switch response.result {
                case .success:
                    if let data=response.data{
                        let response1 = try? JSONDecoder().decode(UpdateModel.self, from: data)
                        if self.compareVersion(str1: response1?.results?[0].version ?? "", str2: localVersion) {
                            self.alertsTwo(url:response1?.results?.first!.trackViewUrl ?? "")
                                            }else{
                                                print("345")
                                            }
                    }
                case .failure:
                    print("ERROR")
                    self.view.makeToast("请求失败")
                }
                
//                print(responses.value!)
//                let resultDict = responses.value as? [String : Any]
//                guard let resultDict = responses.value as? [String : Any], resultDict.keys.count > 0 else {
//                    print("无数据:\(responses)")
//                    return
//                }
//
//                let tempArr = resultDict!["results"] as? [[String: Any]]
//                if let resultsArr = tempArr {
//                    if resultsArr.count < 1 {
//                        print("此APPID为未上架的APP或者查询不到")
//                        return
//                    }
//                    let itunesVersion = resultsArr.first!["version"] as! String
//                    if self.compareVersion(str1: itunesVersion, str2: localVersion) {
//                        print("123")
//                    }else{
//                        print("345")
//                    }
//                }
                
            }
    }
    
    private func compareVersion(str1: String, str2: String) -> Bool {
            let compareResult = str1.compare(str2, options: .numeric, range: nil, locale: nil)
            return (compareResult == .orderedAscending)
        }

    
    //MARK: - 双按钮提示框
    func alertsTwo(url:String){
        let alert:UIAlertController = UIAlertController(title: "有新版本", message: "前去更新版本？", preferredStyle:UIAlertController.Style.alert)
        let noAction = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) in}
        let yesAction = UIAlertAction(title: "更新", style: .destructive) { [self] (UIAlertAction) in
            let updateUrl:URL = URL.init(string: url)!
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(updateUrl, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(updateUrl)
            }
            self.dismiss(animated: true, completion: nil)
        }
        alert.addAction(noAction)
        alert.addAction(yesAction)
        //以模态方式弹出
        self.present(alert, animated: true, completion: nil)
    }
    
    
    let sessionManager: Session = {
        let configuration = URLSessionConfiguration.af.default
        configuration.timeoutIntervalForRequest = 5
        return Session(configuration: configuration)
    }()
    
    var statusBarHeight :Int = 0
    
    let width = Int(UIScreen.main.bounds.size.width)//获取屏幕宽
    let height = UIScreen.main.bounds.size.height//获取屏幕高
    
    let spinner = UIActivityIndicatorView (style: .medium)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        //设置顶部导航栏
        navigationController?.navigationBar.tintColor = .black
        //        let button = UIButton (type: .system)
        //        button.frame = CGRect (x:0,y:0,width:65,height:30)
        //        button.setImage( UIImage (named: "icon_back" ), for : .normal)
        //        button.setTitle("返回", for: .normal)
        //        button.addTarget(self, action: #selector(backItemPressed), for: .touchUpInside)
        //        let leftBarBtn = UIBarButtonItem (customView: button)
        let item = UIBarButtonItem(title: "", style: .plain, target: self, action:#selector(backItemPressed))
        item.image = UIImage(named: "icon_back")
        self.navigationItem.leftBarButtonItem = item
        
        statusBarHeight = Int(UIApplication.shared.statusBarFrame.height) //获取statusBar的高度
        if (navigationController != nil) {
            statusBarHeight+=Int(navigationController!.navigationBar.frame.size.height)
        }
        
    }
    
    @objc func kbFrameChanged(_ notification : Notification){
        let info = notification.userInfo
        let kbRect = (info?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let offsetY = kbRect.origin.y - UIScreen.main.bounds.height
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: offsetY)
        }
    }
    
    @objc func backItemPressed() {
        if let nav = self.navigationController {
            nav.popViewController(animated: true)
        }
    }
    
    func initLoadingView(){
        self.view.addSubview(spinner)
        spinner.backgroundColor = .gray
        spinner.color = .white
        spinner.frame=CGRect.init(origin: CGPoint(x: 0,y: 0), size: CGSize(width: 60, height: 60))
        spinner.layer.cornerRadius = 5.0
        spinner.center=self.view.center
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        navigationController?.interactivePopGestureRecognizer?.isEnabled=false
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    func showAlert(){
        let alertView = UIAlertController.init(title: "提示", message: "确认退出登录么", preferredStyle: .alert)
        let alert = UIAlertAction.init(title: "确定", style: .destructive) { (UIAlertAction) in
            self.backItemPressed()
        }
        let cancleAlert = UIAlertAction.init(title: "取消", style: .cancel) { (UIAlertAction) in
            print("点击取消按钮")
        }
        alertView.addAction(cancleAlert)
        alertView.addAction(alert);
        self.present(alertView, animated: true, completion: nil)
    }
    
    
}
